﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KLADR
{
    public class KLADR
    {
        private string kladr_address_string;
        private AccessKladr accessKladr; // используется только для получения значений по умолчанию классификатора
        private string defaultKladrCode;

        private string region;
        private string district;
        private string city;
        private string town;
        private string street;
        private string house;
        private string flat;

        private string defaultRegion;
        private string defaultDistrict;
        private string defaultCity;
        private string defaultTown;

        private string regionCode;
        private string districtCode;
        private string cityCode;
        private string townCode;

        private void clear()
        {
            regionCode = "";
            districtCode = "";
            cityCode = "";
            townCode = "";
            region = "";
            district = "";
            city = "";
            town = "";
            street = "";
            house = "";
            flat = "";
        }

        public string SqlConnectionString
        {
            set
            {
                if (string.IsNullOrEmpty(value)) return;
                accessKladr.SqlConnectionString = value;
            }
            get
            {
                return accessKladr.SqlConnectionString;
            }
        }

        public void InteractiveEdit()
        {
            FormEditAddress frmEdit = new FormEditAddress();
            frmEdit.SqlConnectionString = SqlConnectionString;
            frmEdit.DefaultKladrCode = defaultKladrCode;
            frmEdit.KladrAddr = kladr_address_string;

            if (frmEdit.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                kladr_address_string = frmEdit.KladrAddr;
                ParseAddressString(kladr_address_string);
            }
        }

        public override string ToString()
        {
            return GetAddressString();
        }

        public string Address
        {
            get
            {
                return kladr_address_string;
            }
            set
            {
                kladr_address_string = value;
                if (kladr_address_string == null) kladr_address_string = "";
                ParseAddressString(kladr_address_string);
            }
        }

        public override bool Equals(object obj)
        {
            if (obj == null || GetType() != obj.GetType()) return false;
            KLADR k = (KLADR)obj;
            return Address.Equals(k.Address);
        }

        public override int GetHashCode()
        {
            return kladr_address_string.GetHashCode();
        }

        public KLADR()
        {
            accessKladr = new AccessKladr();
        }

        public string DefaultKladr
        {
            set
            {
                if (value == null) return;
                defaultKladrCode = value;
                addressItem address;
                string src = value as string;
                if (string.IsNullOrEmpty(src)) return;
                if (src.Length != 11) return;
                regionCode = src.Substring(0, 2);
                districtCode = src.Substring(2, 3);
                cityCode = src.Substring(5, 3);
                townCode = src.Substring(8, 3);
                address = accessKladr.GetRegionByCodeAddress(regionCode);
                defaultRegion = string.Format("{0} {1}", address.name, address.socr).Trim();
                address = accessKladr.GetDistrictByCodeAddress(regionCode, districtCode);
                defaultDistrict = string.Format("{0} {1}", address.name, address.socr).Trim();
                address = accessKladr.GetCityByCodeAddress(regionCode, districtCode, cityCode);
                defaultCity = string.Format("{0} {1}", address.name, address.socr).Trim();
                address = accessKladr.GetTownByCodeAddress(regionCode, districtCode, townCode);
                defaultTown = string.Format("{0} {1}", address.name, address.socr).Trim();
            }
        }

        private string GetAddressString()
        {
            StringBuilder str = new StringBuilder();
            if (!string.IsNullOrEmpty(region))
            {
                if (region.Trim() != defaultRegion)
                    str.Append(string.Format("{0},", region));
            }
            if (!string.IsNullOrEmpty(district))
            {
                if (district.Trim() != defaultDistrict)
                    str.Append(string.Format("{0},", district));
            }
            if (!string.IsNullOrEmpty(city))
            {
                if (city.Trim() != defaultCity)
                    str.Append(string.Format("{0},", city));
            }
            if (!string.IsNullOrEmpty(town))
            {
                if (town.Trim() != defaultTown)
                    str.Append(string.Format("{0},", town));
            }
            if (!string.IsNullOrEmpty(street))
            {
                str.Append(string.Format("{0},", street));
            }
            if (!string.IsNullOrEmpty(house))
            {
                str.Append(string.Format("дом {0},", house));
            }
            if (!string.IsNullOrEmpty(flat))
            {
                str.Append(string.Format("кв. {0},", flat));
            }
            if (str.Length > 0)
                str.Remove(str.Length - 1, 1); // отбрасываем последнюю запятую
            return str.ToString();
        }

        /// <summary>
        /// Удалить из строки все пробелы
        /// </summary>
        /// <param name="src"></param>
        /// <returns></returns>
        private string DropSpaces(string src)
        {
            StringBuilder result = new StringBuilder();
            char[] srclist = src.ToCharArray();
            foreach (char item in srclist)
            {
                if (item == ' ') continue;
                result.Append(item);
            }
            return result.ToString();
        }

        private void ParseAddressString(string address)
        {
            clear();
            address = address.Trim().ToUpper();
            string[] list = address.Split(new char[] { ',' });
            int list_cnt = list.Count();
            if (list_cnt > 0)
            {
                region = (list[0].Trim());
            }
            if (list_cnt > 1)
            {
                district = (list[1].Trim());
            }
            if (list_cnt > 2)
            {
                city = (list[2].Trim());
            }
            if (list_cnt > 3)
            {
                town = (list[3].Trim());
            }
            if (list_cnt > 4)
            {
                street = (list[4].Trim());
            }
            if (list_cnt > 5)
            {
                house = DropSpaces(list[5].Trim());
            }
            if (list_cnt > 6)
            {
                flat = list[6].Trim();
            }

            if (region == defaultRegion && district == defaultDistrict && city == defaultCity && town == defaultTown)
            {
                region = "";
                district = "";
                city = "";
                town = "";
            }
        }
    }
}
